<template>
  <div class="addExpense">
    <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
      <el-row>
        <mainTilte title="基本信息" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="采购单号" prop="purchase_code">
            <el-input v-model.trim="form.purchase_code">
              <el-button slot="append" @click="selectPurchaseClick">选择采购单</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票号" prop="invoice_no">
            <el-input v-model.trim="form.invoice_no" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票日期" prop="invoice_date">
            <el-date-picker v-model="form.invoice_date" type="date" placeholder="发票日期" value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="付款单位" prop="payer">
            <el-input v-model.trim="form.payer" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票税率" prop="rate">
            <!--正则验证input输入，要求只能输入正数，小数点后保留两位-->
            <el-input v-model.trim="form.rate">
              <el-button slot="append">%</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票金额" prop="tax_amount">
            <el-input-number v-model.trim="form.tax_amount" :min="0" :max="9999999999" :precision="2" :controls="false" class="wfull tal" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="未付金额" prop="unpaid_amount">
            <el-input v-model.trim="form.unpaid_amount" maxlength="10" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="供应商" prop="supply">
            <app-select v-model="form.supply" url="/supply" :params="supplyParams" options-label="name" placeholder="请选择供应商" options-value="name" disabled-key="cooperation_status:0" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报关单号" prop="declaration_no">
            <el-input v-model="form.declaration_no" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="备注说明" prop="notes">
            <el-input v-model="form.notes" type="textarea" maxlength="500" autosize />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="发票附件" />
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="上传附件" prop="attachment">
            <uploadFile list-type="text" text="上传支持图片、pdf格式" :file-list="fileList" :upload-limit="1" accept-type="image/jpeg,image/png,application/pdf" @handleImageSuccess="handleImageSuccess" @beforeRemoveFile="beforeRemoveFile" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="dialog-footer-center">
        <span>
          <el-button :loading="canSaveLoading" type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </span>
      </div>
    </el-form>
    <el-dialog
      v-if="dialogAddProductVisible"
      title=""
      :visible.sync="dialogAddProductVisible"
      :close-on-click-modal="false"
      width="90%"
      class="dialogText header-none"
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <div v-loading="loading">

        <el-form ref="searchPurchaseForm" :inline="true" :model="searchPurchaseForm" label-width="110px">
          <div class="filters-wrap clearfix">
            <div class="filters-area">
              <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
                <el-form-item label="">
                  <el-select v-model.trim="searchPurchaseForm.searchType" clearable placeholder="采购单编码">
                    <el-option v-for="(item, index) of issignContract" :key="index" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
                <el-form-item label="">
                  <el-input v-model.trim="searchPurchaseForm.code" placeholder="关键字回车搜索" @keyup.enter.native="query" />
                </el-form-item>
              </el-col>
              <el-button type="primary" icon="el-icon-search" @click="query">搜索</el-button>
            </div>
          </div>
        </el-form>
        <egrid
          v-loading="loading"
          class="egrid"
          stripe
          fit
          border
          highlight-current-row
          element-loading-text="正在努力加载中..."
          :column-type="['selection']"
          :data="tableData"
          :columns="columns"
          :columns-schema="columnsSchema"
          @selection-change="checkIds"
        />
        <epagination v-if="tableData" :total="total" :current="searchPurchaseForm.page" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
        <div class="dialog-footer-center">
          <span>
            <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
            <el-button type="primary" @click="saveData()">确认选择</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import dicValues from '@/components/dicTransform/index'
import { getFileId, filterId, fileTransform } from '@/filters/index'
import { validPrice4 } from '@/utils/validate'
export default {
  name: 'PurchaseInvoiceAdd',
  mixins: [list],
  data() {
    const DICTIONARIES = {
      auditStatus: [
        // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待采购员审核'
        },
        {
          code: 2,
          name: '待运营审核'
        },
        {
          code: 3,
          name: '运营审核通过'
        },
        {
          code: -1,
          name: '采购员审核驳回'
        },
        {
          code: -2,
          name: '运营员审核驳回'
        }
      ],
      // 是否生成合同  0-未生成 1-已生成
      cooperationStatus: [
        { code: 0, name: '未生成' },
        { code: 1, name: '已生成' }
      ]
    }
    return {

      supplyParams: {
        page: 1,
        limit: 100000000,
        audit_status: 2
      },

      canSaveLoading: false,
      loadingText: '',
      form: {
        purchase_code: '', // 采购单号 多个采购单号已逗号隔开
        invoice_no: '', // 发票号
        invoice_date: '', // 发票日期
        payer: '', // 付款单位
        rate: '', // 发票税率
        tax_amount: '', // 税额
        unpaid_amount: '', // 未付金额
        supply: '', // 供应商名称
        declaration_no: '', // 报关单号
        notes: '', // 备注
        attachment: '' // 附件
      },
      roleCodeRule: {
        purchase_code: [
          { required: true, message: '请选择采购单号', trigger: 'change' }
        ],
        invoice_no: [
          { required: true, message: '请填写发票号', trigger: 'blur' },
          { max: 30, message: '发票号必须在30个字符以内', trigger: 'blur' }
        ],
        invoice_date: [
          { required: true, message: '请填写发票号', trigger: 'change' }
        ],
        payer: [
          { required: true, message: '请填写付款单位', trigger: 'blur' },
          { max: 50, message: '付款单位必须在50个字符以内', trigger: 'blur' }
        ],
        rate: [
          { required: true, message: '请填写发票税率', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (!validPrice4(value)) {
                callback(new Error('发票税率必须为百分数，且保留四位小数'))
              } else if (value < 0 || value > 100) {
                callback(new Error('发票税率必须[0, 100]之间'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }

        ],
        tax_amount: [
          { required: true, message: '请填写发票金额', trigger: 'blur' }
        ],
        unpaid_amount: [
          { required: true, message: '请填写未付金额', trigger: 'blur' }
        ],
        supply: [
          { required: true, message: '请填写供货商', trigger: 'blur' }
        ],
        declaration_no: [
          { required: true, message: '请输入报关单号', trigger: 'blur' },
          { max: 50, message: '报关单号必须在50个字符以内', trigger: 'blur' }
        ],
        attachment: [
          { required: true, message: '请上传供货商附件', trigger: 'change' }
        ]
      },
      fileList: [],

      dialogAddProductVisible: false,
      searchPurchaseForm: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        code: '',
        audit_status: 3,
        searchType: 'code'
      },
      issignContract: [
        {
          name: '采购单编码',
          code: 'code'
        },
        {
          name: '合同编码',
          code: 'contract_code'
        }
      ],
      statusType: [
        // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '待采购员审核'
        },
        {
          code: 2,
          name: '待运营审核'
        },
        {
          code: 3,
          name: '运营审核通过'
        },
        {
          code: -1,
          name: '采购员审核驳回'
        },
        {
          code: -2,
          name: '运营员审核驳回'
        }
      ],
      /** *
       * 定义显示的表格
       */
      columns: [
        {
          label: '采购申请单编码',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '采购员',
          prop: 'buyer',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '采购总金额',
          prop: 'amount',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核状态',
          prop: 'audit_status',
          width: '150',
          align: 'center',
          tooltip: false
        },
        {
          label: '是否生成采购合同',
          prop: 'contract_status',
          width: '230',
          align: 'center',
          tooltip: false
        },
        {
          label: '合同编码',
          prop: 'contract_code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'created_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '所属组织',
          prop: 'organization',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'updated_by_name',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      /** *
       * 字典表组件
       */
      columnsSchema: {
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        是否生成采购合同: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      isEdit: false
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.initTableData(
      `/purchase-order?page=${this.searchPurchaseForm.page}&limit=${this.searchPurchaseForm.limit}&code=${this.searchPurchaseForm.code}&audit_status=${this.searchPurchaseForm.audit_status}`
    )
  },
  mounted() {
    if (this.$route.query && this.$route.query.row) {
      this.form = JSON.parse(this.$route.query.row)
      console.log(this.form, 'this.form >>>>')
      this.fileList = []
      this.fileList = fileTransform(this.form.attachment)
      this.isEdit = true
    }
  },
  methods: {
    cancel() {
      this.$router.push({ path: '/supplyChain/purchaseInvoice' })
    },
    handleImageSuccess({ name, url }) {
      this.fileList.push({ name, url })
      this.form.attachment = getFileId(this.fileList)
    },
    beforeRemoveFile() {
      this.fileList = filterId(this.fileList)
      this.form.attachment = getFileId(this.fileList)
    },
    selectPurchaseClick() {
      this.searchPurchaseForm.page = 1
      this.searchPurchaseForm.limit = 10
      this.searchPurchaseForm.totalRows = 0
      this.searchPurchaseForm.code = ''
      this.initTableData(
        `/purchase-order?page=${this.searchPurchaseForm.page}&limit=${this.searchPurchaseForm.limit}&code=${this.searchPurchaseForm.code}&audit_status=${this.searchPurchaseForm.audit_status}`
      )
      this.dialogAddProductVisible = true
    },
    query() {
      let code = ''
      let code1 = ''
      console.log('this.searchPurchaseForm.searchType', this.searchPurchaseForm.searchType)
      if (this.searchPurchaseForm.searchType === 'code') {
        code1 = this.searchPurchaseForm.code
      } else {
        code = this.searchPurchaseForm.code
      }
      this.initTableData(
        `/purchase-order?page=${this.searchPurchaseForm.page}&limit=${this.searchPurchaseForm.limit}&code=${code1}&contract_code=${code}&audit_status=${this.searchPurchaseForm.audit_status}`
      )
    },
    saveData() {
      const that = this
      const dataLength = that.checkedList.length
      if (dataLength === 0) {
        that.$message.error('最少选择一条数据')
        return false
      }
      const newArr = that.checkedList.map((item) => {
        return item.code
      })
      that.form.purchase_code = newArr.join(',')
      that.dialogAddProductVisible = false
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.canSaveLoading = true
          const params = Object.assign({}, this.form)
          delete params.created_at
          delete params.updated_at
          if (this.isEdit) {
            this.$http
              .put(`/purchase-invoice/${this.form.id}`, params)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('修改成功')
                  this.cancel()
                }
                this.canSaveLoading = false
              })
              .catch(() => {
                this.loading = false
                this.canSaveLoading = false
              })
          } else {
            this.$http
              .post(`/purchase-invoice`, params)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('新增成功')
                  this.cancel()
                }
                this.canSaveLoading = false
              })
              .catch(() => {
                this.loading = false
                this.canSaveLoading = false
              })
          }
          this.$router.push('/supplyChain/purchaseInvoice')
        }
      })
    },
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.searchPurchaseForm.page = val
      this.initTableData(
        `/purchase-order?page=${this.searchPurchaseForm.page}&limit=${this.searchPurchaseForm.limit}&code=${this.searchPurchaseForm.code}&audit_status=${this.searchPurchaseForm.audit_status}`
      )
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
/deep/.el-select,
.el-autocomplete,
.el-date-editor {
  width: 100%;
}
</style>
